#include "stdafx.h"
#include "ThreadTests.h"
#include "LoadTests.h"
#include <process.h>
#include "criticalsection.h"
CRITICAL_SECTION      g_critRegion; 

unsigned __stdcall Dynamic_Thread_Procedure(LPVOID foo)
{
	EnterCriticalSection(&g_critRegion);
	bool* resolve = (bool*)(foo);
	RunMfcDllTest(*resolve); // Leaks 7 allocs
	LeaveCriticalSection(&g_critRegion); 
	return 0;
}

void RunLoaderLockTests(bool resolve)
{
	InitializeCriticalSection(&g_critRegion);
	static const int NUMTHREADS = 3;
	HANDLE threads[NUMTHREADS] = {0};
	unsigned thread_id = NULL;

	for (UINT i = 0; i < NUMTHREADS; ++i)
	{
		threads[i] = (HANDLE)_beginthreadex(NULL, // security attribute
			0,                          // stack size
			Dynamic_Thread_Procedure,           // start function
			&resolve,                   // thread parameters
			0,                          // creation flags
			&thread_id);                // thread id
	}

	BOOL wait_for_all = TRUE;
	DWORD result = WaitForMultipleObjects(NUMTHREADS, threads, wait_for_all, INFINITE);
	switch (result)
	{
	case WAIT_OBJECT_0:
		_tprintf(_T("All threads finished correctly.\n"));
		break;
	case WAIT_ABANDONED_0:
		_tprintf(_T("Abandoned mutex.\n"));
		break;
	case WAIT_TIMEOUT:
		_tprintf(_T("All threads timed out\n"));
		break;
	case WAIT_FAILED:
		{
			_tprintf(_T("Function call to Wait failed with unknown error\n"));
			TCHAR lpMsgBuf[MAX_PATH] = {0};
			FormatMessage(
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				GetLastError(),
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				lpMsgBuf,
				MAX_PATH,
				NULL );
	
			_tprintf(_T("%s"), lpMsgBuf);
		}

		break;
	default:
		_tprintf(_T("Some other return value\n"));
		break;
	}

}
